window.addEventListener('DOMContentLoaded', () => {
  app.initPage();
});

function loadPage() {
  $.get(`${app.urlLocation.queryAllTest}/${app.pageHelper.global_page}/${app.pageHelper.global_limit}`, {
    clazz: ''
  }, res => {
    if (res.data.length === 0 && app.pageHelper.global_page > 1) {
      app.pageHelper.global_page--;
      loadPage();
    } else {
      loadTpTable(res);
      loadTpPage(res);
    }
  })
}

function loadTpTable(tps) {
  layui.use(['element', 'table', 'layer'], () => {
    let table = layui.table,
      layer = layui.layer;
    table.render({
      elem: '#result',
      data: tps.data,
      limit: app.pageHelper.global_limit,
      cols: [
        [
          {field: 'testId', title: '试卷编号', width: 295},
          {field: 'testTitle', title: '试卷名称'},
          {field: 'testClazz', title: '科目'},
          {
            field: 'testTime', title: '考试时间', templet: d => {
              return `${d.testTime} 分钟`;
            }
          },
          {field: 'createdBy', title: '创建人'},
          {
            field: 'createdTime', title: '创建时间', width: 190, templet: d => {
              return app.formatDate(new Date(d.createdTime));
            }
          },
          {title: '操作', toolbar: '#test-tool'}
        ]
      ]
    });
    table.on('tool(result)', obj => {
      if (obj.event === 'detail') {
        let data = obj.data;
        $.get(`${app.urlLocation.queryTpDetail}`, {testId: data.testId}, res => {
          if (res.apList.length === 0) {
            layer.msg('该试卷还没有学生作答，未生成相关记录');
          } else {
            console.info(data.testId);
            // localStorage.setItem('testId', data.testId);
            // window.location.href = '/teacher-action/check-detail';
          }
        })
      }
    })
  })
}

function loadTpPage(tps) {
  layui.use('laypage', () => {
    layui.laypage.render({
      elem: 'result-page',
      curr: app.pageHelper.global_page,
      count: tps.count,
      limit: app.pageHelper.global_limit,
      limits: [10, 20, 30, 40, 50],
      layout: ['count', 'prev', 'page', 'next', 'limit'],
      jump: function (obj, first) {
        if (!first) {
          app.pageHelper.global_page = obj.curr;
          app.pageHelper.global_limit = obj.limit;
          loadPage();
        }
      }
    });
  })
}